<?

class rss
{
	const CACHE = 3600;

	public static function fetch( $url, $cache = null )
	{
		$key = 'rss:' . $url;
		if ( ($list = cache::get($key)) !== false ) return $list;

		if ( !$data = file_get_contents($url) )
		{
			cache::set($key, null, 60);
			return;
		}

		if ( !$xml = simplexml_load_string($data) )
		{
			cache::set($key, null, 60);
			return;
		}

		foreach ( $xml->channel->item as $item )
			$list[] = self::item($item);

		cache::set($key, $list, self::CACHE);
		return $list;
	}

	protected static function item( $item )
	{
		$data['title'] = (string)$item->title;
		$data['text'] = self::description((string)$item->description);
		$data['description'] = (string)$item->description;
		$data['url'] = (string)$item->link;
		$data['ts'] = strtotime((string)$item->pubDate);
		$data['guid'] = (string)$item->guid;

		if ( preg_match('/img src="(.+?)"/', $item->description, $m) )
			$data['img'] = $m[1];

		return $data;
	}

	protected static function description( $html )
	{
		if ( preg_match_all('/<font.+?>(.+?)<\/font>/misu', $html, $m) )
		{
			$html = '';
			foreach ( $m[1] as $match )
			{
				$match = strip_tags($match);
				if (strlen($html) < strlen($match) )
					$html = $match;
			}
		}

		return strip_tags($html);
	}
}